package test

import (
	"fmt"
	"gorm/internal/database"
	"gorm/internal/domain"
)

func Multilist() {
	db := database.DB

	db.AutoMigrate(&domain.User{}, &domain.Article{}, &domain.Profile{}, &domain.Tag{})

	fmt.Println("\n-- 创建关联数据 --")
	tag1 := domain.Tag{Name: "go"}
	tag2 := domain.Tag{Name: "gorm"}

	user := domain.User{
		Name:    "zhangsan",
		Profile: domain.Profile{Email: "zhangsan@qq.con"},
		Articles: []domain.Article{
			{Title: "gorm基础", Content: "...", Tags: []domain.Tag{tag1, tag2}},
			{Title: "go 语言入门", Content: "...", Tags: []domain.Tag{tag1}},
		},
	}
	db.Create(&user)
	fmt.Println("成功创建了用户及其关联的文章、资料和标签。")

	fmt.Println("\n-- 查询关联数据 --")
	var retrievedUser domain.User
	result := db.Preload("Profile").Preload("Articles").Preload("Articles.Tags").First(&retrievedUser, user.ID)

	if result.Error != nil {
		panic("查询用户失败")
	}

	fmt.Printf("查询到的用户名: %s\n", retrievedUser.Name)
	fmt.Printf(" |- 邮箱: %s\b", retrievedUser.Profile.Email)
	for _, article := range retrievedUser.Articles {
		fmt.Printf(" |- 文章: %s\n", article.Title)
		var tagNames []string
		for _, tag := range article.Tags {
			tagNames = append(tagNames, tag.Name)
		}

		fmt.Printf(" |-标签: %v\n", tagNames)
	}

}
